<template>
  <div id="distribution24hStats">
    <DecorativeTitle :text="'24小时分布（' + activeChart + '）'" />
    <div class="d-flex" style="height: 45px;">
      <div>
        <el-radio-group v-model="activeChart" size="mini">
          <el-radio-button label="呼入量"></el-radio-button>
          <el-radio-button label="出车量"></el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div style="margin-top: 5px;">
      <Distribution24hHrs :cdata="hrsData" v-if="activeChart === '呼入量'" />
      <Distribution24hCcs :cdata="ccsData" v-else />
    </div>
  </div>
</template>
<script>
import bus from "@/bus";
import config from "@/config";
import DecorativeTitle from "@/components/DecorativeTitle.vue";
import Distribution24hHrs from "./Distribution24hHrs.vue";
import Distribution24hCcs from "./Distribution24hCcs.vue";
import {getUnitCalItemsWithNoAuthorization} from "@/api/UnitCalculate";
import {getLast24HoursRange} from "@/utils/dateUtil";

export default {
  components: {
    DecorativeTitle,
    Distribution24hHrs,
    Distribution24hCcs
  },
  data() {
    return {
      activeChart: '呼入量',
      totalHrs: 0,
      totalCcs: 0,
      hrsData: {
        categories: [],
        total: []
      },
      ccsData: {
        categories: [],
        total: []
      },
      standardData: {
        beginDateTime: '',
        endDateTime: '',
        columnsData: [
          {
            columnHeadType: 1,
            commGroupInfo: {
              isCommonGroup: true,
              category: "TIMEGROUP",
              categoryGroup: "TIMESLICING_1"
            },
            dataIndex: "TIMEGROUP"
          },
          {
            columnHeadType: 1,
            calculateIden: {
              title: "呼入数"
            },
            calculateInfo: {
              offset: 0,
              dataCategory: 0,
              valueCategory: 0,
              count: true,
              differenceCount: false,
              proportion: false
            },
            dataIndex: "HRS"
          },
          {
            columnHeadType: 1,
            calculateIden: {
              title: "出车数"
            },
            calculateInfo: {
              offset: 0,
              dataCategory: 0,
              valueCategory: 0,
              count: true,
              differenceCount: false,
              proportion: false
            },
            dataIndex: "CCS"
          }
        ],
        verticalGroups: [
          {
            category: "TIMESLICING",
            categoryGroup: "TIMESLICING_1",
            level: 1,
            title: "一个时间段（一组）"
          }
        ],
        screens: [
          {
            ref: "EPAIAREA_CODE",
            checkIden: "EPAIAREA_CODE_1",
            rlevantData: {
              iden: "EPAIAREA_CODE_1",
              filterType: 2,
              value: [
                {
                  value: config.xzbm,
                  xzbm: config.xzbm
                }
              ]
            }
          }
        ]
      }
    }
  },
  async created() {
    this.fetchData()
    // 监听全局刷新事件
    this.refreshHandler = () => {
      console.log("定时刷新：Distribution24hStats")
      this.fetchData();
    }
    bus.$on('refresh-all-data', this.refreshHandler)
  },
  methods: {
    async fetchData() {
      const { beginDateTime, endDateTime } = getLast24HoursRange();
      this.standardData.beginDateTime = beginDateTime;
      this.standardData.endDateTime = endDateTime;
      const res = await getUnitCalItemsWithNoAuthorization(this.standardData);
      if (res.code === 200 && res.isSuccess) {
        try {
          const entityList = JSON.parse(res.entity);
          if (entityList && entityList.length > 0) {
            // 分离合计项和普通项
            const totalItem = entityList.find(item => item.TIMEGROUP === '合计');
            const normalItems = entityList.filter(item => item.TIMEGROUP !== '合计' && item.TIMEGROUP); // 排除空类型
            // 设置总数（优先使用合计项，没有则计算总和）
            this.totalHrs = totalItem
                ? Number(totalItem.HRS)
                : normalItems.reduce((sum, item) => sum + Number(item.HRS), 0);
            this.totalCcs = totalItem
                ? Number(totalItem.CCS)
                : normalItems.reduce((sum, item) => sum + Number(item.CCS), 0);
            const categories = normalItems.map(item => item.TIMEGROUP);
            const totalArrayHrs = normalItems.map(item => item.HRS);
            const totalArrayCcs = normalItems.map(item => item.CCS);
            this.hrsData = {
              categories: categories,
              total: totalArrayHrs
            }
            this.ccsData = {
              categories: categories,
              total: totalArrayCcs
            }
            console.log("this.hrsData: ", this.hrsData)
          } else {
            this.totalHrs = 0;
            this.totalCcs = 0;
            const categories = this.getLast24Hours();
            this.hrsData = {
              categories: categories,
              total: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            }
            this.ccsData = {
              categories: categories,
              total: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
            }
          }
        } catch (e) {
          console.error('entity 解析失败', e);
          this.resetData();
        }
      }
    },
    // 重置数据
    resetData() {
      this.totalHrs = 0;
      this.totalCcs = 0;
      this.hrsData = {
        categories: [],
        total: []
      }
    },
    getLast24Hours() {
      const now = new Date();
      const currentHour = now.getHours();
      const result = [];
      for (let i = 0; i < 24; i++) {
        let hour = (currentHour - 1 - i + 24) % 24;
        result.push(`${hour}(H)`);
      }
      return result.reverse();
    }
  },
  beforeDestroy() {
    bus.$off('refresh-all-data', this.refreshHandler)
  }
}

</script>

<style lang="scss" scoped>
#distribution24hStats {
  .d-flex {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
